<?php
namespace HakugyokuSoulMVC;

class HakugyokuSoulMVC {
	protected $config;
	
	function __construct($config) {
		$this->config = $config;
	}
	
	public function run(){
		$this->isDebug();
		$this->getConf();
		$this->route();
	}
	
	
	public function route(){
		// $_SERVER['REQUEST_URI'];  不适合iis
		$urlParam = @$_SERVER['HTTP_X_ORIGINAL_URL'];
		
		//跳转默认页
		if(isset($urlParam) == FALSE){
			$arr = array();
			$this->runController(MVC_CONTROLLER,MVC_ACTION,$arr);
			return;
		}
		
		// 删除前后的“/”
        $urlParam = trim($urlParam, '/');
        
        // 使用“/”分割字符串，并保存在数组中
        $urlArray = explode('/', $urlParam);
        // 删除空的数组元素
        $urlArray = array_filter($urlArray);
        
        // 获取控制器名
        $controllerName = ucfirst($urlArray[0]);
        
        // 获取动作名
        array_shift($urlArray);
        $actionName = $urlArray ? $urlArray[0] : $actionName;
        
        // 获取URL参数
        array_shift($urlArray);
		
        $urlParam = $urlArray ? $urlArray : array();
        
        $this->runController($controllerName,$actionName,$urlParam);
	}
	
	
	protected function runController($controllerName,$actionName,$urlParam){
		$controllerName = $controllerName."Controller";
		
		//判断文件
		if(is_file(APP_PATH."application/controllers/$controllerName".".php")){
			include(APP_PATH."application/controllers/$controllerName".".php");
		}else{
			exit($controllerName.'控制器文件不存在');
		}
		
		if(!class_exists("application\\Controllers\\".$controllerName)){
			exit($controllerName.'控制器不存在');
		}
		
		if (!method_exists("application\\Controllers\\".$controllerName, $actionName)) {
            exit($actionName . '方法不存在');
        }
        
        $controllerNoPath = $controllerName;
        $controllerName = "application\\Controllers\\".$controllerName;
		
		$controller = new $controllerName($controllerNoPath,$actionName,$urlParam);
		$controller->$actionName();
	}
	
	
	// 检测开发环境
    public function isDebug(){
        if (APP_DEBUG === true) {
            error_reporting(E_ALL);
            ini_set('display_errors','On');
        } else {
            error_reporting(E_ALL);
            ini_set('display_errors','Off');
            ini_set('log_errors', 'On');
        }
    }
    
    public function getConf(){
		define("DB_HOST",$this->config['db']['host']);
		define("DB_NAME",$this->config['db']['dbname']);
		define("DB_USER",$this->config['db']['username']);
		define("DB_PASS",$this->config['db']['password']);
		define("DB_PORT",$this->config['db']['port']);
		
		define("WEB_TITLE",$this->config['web']['title']);
		
		define("MVC_CONTROLLER",$this->config['mvc']['defaultController']);
		define("MVC_ACTION",$this->config['mvc']['defaultAction']);
	}
    
}